<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>咨询师管理</el-breadcrumb-item>
		<el-breadcrumb-item>订单管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="咨询师名称">
			<el-input v-model="queryInfo.counselor.counselorName" placeholder="请输入咨询师名称" clearable
				@clear="queryDataList()" />
		</el-form-item>
		<el-form-item label="用户名">
			<el-input v-model="queryInfo.user.username" placeholder="请输入用户名" clearable @clear="queryDataList()" />
		</el-form-item>
		<el-form-item label="收费类别">
			<el-input v-model="queryInfo.counselorPriceClassify.priceClassifyName" placeholder="请输入收费类别" clearable
				@clear="queryDataList()" />
		</el-form-item>
		<el-form-item label="金额">
			<el-input v-model="queryInfo.realPay" placeholder="请输入金额" clearable @clear="queryDataList()" />
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="queryDataList()">搜索</el-button>
			<el-button type="danger" @click="batchRemove()">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-table ref="multipleTableRef" :data="dataList" row-key="id" style="width: 100%"
		@selection-change="handleSelectionChange">
		<el-table-column fixed="left" type="selection" width="55" />
		<el-table-column fixed="left" property="id" label="ID" width="60" />
		<el-table-column property="counselorPriceClassify.priceClassifyName" label="收费类别"
			align="center"></el-table-column>
		<el-table-column property="realPay" label="金额" align="center"></el-table-column>
		<el-table-column property="user.username" label="用户名" align="center"></el-table-column>
		<el-table-column property="counselor.counselorName" label="咨询师名称" align="center"></el-table-column>

		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<div class="demo-pagination-block">
		<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
			:page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="totalNumber"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" />
	</div>

	<el-dialog :title="title" v-model="dialogVisible" width="950" @close="cancle()">
		<el-form :model="counselorData" label-width="100">
			<el-form-item label="咨询师名称">
				<el-input v-model="counselorData.counselorName" autocomplete="off" placeholder="请输入咨询师名称"></el-input>
			</el-form-item>
			<el-form-item label="用户名">
				<el-input v-model="counselorData.username" placeholder="请输入用户名"></el-input>
			</el-form-item>
			<el-form-item label="金额">
				<el-input v-model="counselorData.price" placeholder="请输入金额"></el-input>
			</el-form-item>
			<el-form-item label="收费类别">
				<el-input v-model="counselorData.classify" placeholder="请输入收费类别"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="cancle()">取 消</el-button>
			<el-button type="primary" @click="confirm()">确 定</el-button>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';
	import qs from 'qs'; // 引入qs库处理参数序列化

	// 类型定义（增强代码可读性）
	interface Counselor {
		counselorName : string;
	}
	interface User {
		username : string;
	}
	interface PriceClassify {
		priceClassifyName : string;
	}

	// 全局 axios 实例
	const { appContext } = getCurrentInstance()!;
	const axios = appContext.config.globalProperties.axios;

	// 查询参数（嵌套结构）
	const queryInfo = reactive({
		counselor: {} as Counselor,
		user: {} as User,
		counselorPriceClassify: {} as PriceClassify,
		realPay: '',
		pageNum: 1,
		pageSize: 10
	});

	// 数据列表和总数
	const dataList = ref([]);
	const totalNumber = ref(0);

	// 对话框相关
	const dialogVisible = ref(false);
	const title = ref('新增订单');
	const counselorData = ref({
		counselorName: "",
		username: "",
		price: "",
		classify: "",
		id: ""
	});

	// 批量选择的ID
	const multipleSelection = ref<number[]>([]);

	// 查询数据列表（核心：使用qs序列化参数为点号格式）
	const queryDataList = () => {
		axios.get('counselorOrder/page', {
			params: queryInfo,
			// 关键配置：将嵌套参数序列化为点号格式（如counselor.counselorName）
			paramsSerializer: (params) => {
				return qs.stringify(params, {
					allowDots: true, // 嵌套对象用点号分隔（解决方括号问题）
					encode: true // 确保特殊字符编码
				});
			}
		}).then((resp) => {
			console.log('后端响应:', resp);
			if (resp.code === 200) {
				// 根据后端实际响应调整数据路径（此处假设数据在resp.data.list）
				dataList.value = resp.data.list || [];
				totalNumber.value = resp.data.total || 0;
			} else {
				ElMessage.error('查询失败: ' + (resp.message || resp.msg || '未知错误'));
			}
		}).catch((err) => {
			console.error('请求错误:', err);
			ElMessage.error('网络错误，请重试');
		});
	};

	// 分页处理（修正：更新分页参数）
	const handleSizeChange = (val : number) => {
		queryInfo.pageSize = val; // 更新页大小
		queryInfo.pageNum = 1; // 重置页码为1
		queryDataList();
	};
	const handleCurrentChange = (val : number) => {
		queryInfo.pageNum = val; // 更新页码
		queryDataList();
	};

	// 表格选择变化
	const handleSelectionChange = (val : any[]) => {
		multipleSelection.value = val.map(item => item.id);
	};

	// 单个删除
	const remove = (id : number) => {
		ElMessageBox.confirm(
			'此操作将永久删除，是否继续?',
			'提示',
			{ type: 'warning' }
		).then(() => {
			axios.delete(`counselorOrder/${id}`).then((resp) => {
				if (resp.code === 200) {
					ElMessage.success('删除成功');
					queryDataList();
				} else {
					ElMessage.error('删除失败: ' + (resp.message || '未知错误'));
				}
			});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	// 批量删除
	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请先选择要删除的记录');
			return;
		}
		ElMessageBox.confirm(
			`确定删除选中的 ${multipleSelection.value.length} 条记录?`,
			'提示',
			{ type: 'warning' }
		).then(() => {
			axios.delete('counselorOrder', {
				params: { ids: multipleSelection.value.join(',') }
			}).then((resp) => {
				if (resp.code === 200) {
					ElMessage.success('批量删除成功');
					queryDataList();
				} else {
					ElMessage.error('批量删除失败: ' + (resp.message || '未知错误'));
				}
			});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	// 对话框取消
	const cancle = () => {
		counselorData.value = {
			counselorName: "",
			username: "",
			price: "",
			classify: "",
			id: ""
		};
		dialogVisible.value = false;
	};

	// 对话框确认（新增/修改）
	const confirm = () => {
		if (counselorData.value.id) {
			// 修改订单（统一接口路径为counselorOrder）
			axios.put('counselorOrder', counselorData.value).then((resp) => {
				if (resp.code === 200) {
					ElMessage.success('修改成功');
				} else {
					ElMessage.error('修改失败: ' + (resp.message || '未知错误'));
				}
				queryDataList();
				dialogVisible.value = false;
			});
		} else {
			// 新增订单（统一接口路径为counselorOrder）
			axios.post('counselorOrder', counselorData.value).then((resp) => {
				if (resp.code === 200) {
					ElMessage.success('新增成功');
				} else {
					ElMessage.error('新增失败: ' + (resp.message || '未知错误'));
				}
				queryDataList();
				dialogVisible.value = false;
			});
		}
	};

	// 页面加载时查询数据
	onMounted(() => {
		queryDataList();
	});
</script>

<style>
	.el-breadcrumb {
		border-bottom: 1px solid #eeeeee;
		padding-bottom: 20px;
		margin-bottom: 20px;
	}

	.el-form {
		border: 1px solid #f5f5f5;
		padding: 15px;
		margin-bottom: 20px;
	}

	.demo-pagination-block {
		margin-top: 20px;
		text-align: right;
	}
</style>